package com.tdkj.task;

import java.math.BigInteger;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tdkj.model.user.BeanExperienceAndIntegralCount;
import com.tdkj.service.user.IBeanExperienceAndIntegralCountLogService;
import com.tdkj.service.user.IBeanExperienceAndIntegralCountService;
import com.tdkj.service.user.IBeanUserExperienceService;

public class ExperienceAndIntegralCountTask {
    private static final Logger logger = LoggerFactory.getLogger(ExperienceAndIntegralCountTask.class);
    
    private IBeanExperienceAndIntegralCountLogService logService;
 
    @Resource
	public void setLogService(IBeanExperienceAndIntegralCountLogService logService) {
		this.logService = logService;
	}

    private IBeanExperienceAndIntegralCountService service;
    
    @Resource
	public void setService(IBeanExperienceAndIntegralCountService service) {
		this.service = service;
	}
    
    
    private IBeanUserExperienceService userExperienceService;
    
    @Resource
	public void setUserExperienceService(IBeanUserExperienceService userExperienceService) {
		this.userExperienceService = userExperienceService;
	}
    

	public void execute() {
    	while(true){
    		Long sleepMillis = 2L*60*1000;
    			
			List<BeanExperienceAndIntegralCount> beans = service.findAll(BeanExperienceAndIntegralCount.class);
    		
			for(BeanExperienceAndIntegralCount count : beans){
				
				String sql = " select id, "+count.getRefTableUserColumn() + " as user_id,"+count.getRefTableQuantityColumn() + " as quantity from " + count.getRefTable();
				if(count.getConditionString() != null && !"".equals(count.getConditionString())){
					sql = sql + " where " + count.getConditionString();
				}
				
				sql = " select tt1.id,tt1.user_id,tt1.quantity from ("+ sql +") tt1 left join (select t1.* from xnky_experience_and_integral_count_log t1,xnky_experience_and_integral_count t2 where t1.count_id=t2.id and t2.code='"+count.getCode()+"') tt2 on (tt1.id=tt2.refId) where tt2.id is null";
				
				List<Object> userIdObjects = service.findBySql(sql);
				for(Object object : userIdObjects){
					Object[] result = (Object[])object;
					Long id = ((BigInteger)result[0]).longValue();
					Long userId = ((BigInteger)result[1]).longValue();
					Integer quantity = (Integer)result[2];
					
					logService.createCountLog(count.getId(), userId, id, quantity);
				}
			}
			
    		try {
    			//睡眠时间
				Thread.sleep(sleepMillis);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
}
